package cn.felord.sentinel.configuration;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

import static com.alibaba.csp.sentinel.slots.block.RuleConstant.CONTROL_BEHAVIOR_DEFAULT;

@Configuration(proxyBeanMethods = false)
public class SentinelAspectConfiguration implements InitializingBean {

    @Bean
    public SentinelResourceAspect sentinelResourceAspect() {
        return new SentinelResourceAspect();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        // 规则对应的类为FlowRule，用List保存，可以有多个规则
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        // 设置资源名称
        flowRule.setResource("bar");
        // QPS为2
        flowRule.setCount(2);
        // 需要在限流过滤器中设置对应的解析策略来获取
        // flowRule.setLimitApp(appName);
        //限流的类型
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setControlBehavior(CONTROL_BEHAVIOR_DEFAULT);
        rules.add(flowRule);
        FlowRuleManager.loadRules(rules);
    }
}
